package com.amit.servlet;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet 
{
	public UploadServlet()
	{
		System.out.println("UploadServlet constructor.....");
	}
	
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String ctxPath=request.getRealPath("/");
		File dir=new File(ctxPath, "uploaded");
		
		if(!dir.exists())
		{
			dir.mkdir();
		}
		
		Writer out=response.getWriter();
		boolean uploadData=ServletFileUpload.isMultipartContent(request);
		if(uploadData)
		{
			System.out.println("hello");
			DiskFileItemFactory factory=new DiskFileItemFactory();
			factory.setSizeThreshold(1024*1024*10);
			factory.setRepository(new File("D:\\temp"));
			
			ServletFileUpload upload=new ServletFileUpload(factory);
			upload.setSizeMax(1024*1024*50);
			try
			{
				List<FileItem> fileitems=upload.parseRequest(request);
				Iterator<FileItem> i=fileitems.iterator();
				while(i.hasNext())
				{
					FileItem fi=i.next();
					if(!fi.isFormField())
					{
						String fieldName=fi.getFieldName();
						String fileName=fi.getName();
						String contentType=fi.getContentType();
						boolean isInMemory=fi.isInMemory();
						long sizeInBytes=fi.getSize();
						StringTokenizer tok=new StringTokenizer(fileName, "/");
						String fileToWrite=" ";
						while(tok.hasMoreElements())
						{
							fileToWrite=tok.nextToken();
							
						}
						
						File file=new File(dir, fileToWrite);
						fi.write(file);
					}
				}
			}
			catch (Exception e) {
				
				e.printStackTrace();
			}
			System.out.println("Hello");
			out.write("<h1>File Uploaded in<br/>"+dir.getAbsolutePath());
		}
		else
		{
			out.write("No File Uploaded");
		}
		
	}
	
}
